var SceneWallLibrary = function(options) {
	this.ctx = options.ctx;
	this.editor = options.editor;
	this.globe = options.editor.globe;
	this.sceneId = options.sceneId;
	this.isOpen = false;
}

SceneWallLibrary.prototype.open = function() {
	var _this = this;
	if (_this.isOpen) {
		return;
	}
	layer.load(2);
	var res = common_ajax.ajaxFunc('get', _this.ctx + "/scene/wall/library", {}, "html", null);
	layer.closeAll('loading');
	if (!res) {
		layer.alert('系统异常！');
		return;
	}
	
	layer.closeAll();
	layer.open({
		id: 'SceneWallLibrary',
		title: '折线库',
		type: 1,
		area: '220px',
		content: res,
		shade: 0,
		offset: 'l',
		skin: 'layui-layer layui-layer-adminRight layui-layer-city',
		success: function(layero, dIndex) {
			_this.isOpen = true;
			_this.dIndex = dIndex;
			$(layero).children('.layui-layer-content').css('overflow', 'hidden');
			$(layero).children('.layui-layer-content').css('height', 'calc(100% - 30px)');
			form.render();
			$(".IconImageList>.content>.item>.icon").on('click', function() {
				_this.add($(this).attr('id'));
			})
		},
		end: function() {
			_this.isOpen = false;
			_this.dIndex = null;
			if(_this.drawWall){
				_this.drawWall.destroy();
				_this.drawWall=null;
			}
		}
	});
}


SceneWallLibrary.prototype.add=function(color){
	let _this=this;
	if(_this.drawWall){
		_this.drawWall.destroy();
		_this.drawWall=null;
	}
	let options={
		id:	_this.globe.getUuid(),
		name:'',
		url:_this.ctx,
		code:"",
		type:'Polyline',
		thing:{
			color:color,
		}
	}
	_this.drawWall=_this.globe.drawWall(options);
	_this.drawWall.addListener('success',function(positions){
		if(positions){
            var formData={}; 
            formData['sceneWall.id']=options.id;
            formData['sceneWall.name']='';
            formData['sceneWall.code']='';
            formData['sceneWall.type']='Wall';
            formData['sceneWall.color']=color;
            formData['sceneWall.positions']=JSON.stringify(positions);
            formData['sceneWall.sceneId']=_this.sceneId;
            layer.load(2);
			var res = common_ajax.ajaxFunc('get', _this.ctx + "/scene/wall/save",formData, "json", null);
			layer.closeAll('loading');
			if(200==res.code){
				layer.msg(res?res.message:'系统异常!', {icon: 1});
				_this.globe.render({
	            	id:res.data.id,
	            	name:res.data.name,
	            	code:res.data.code,
	            	type:'Wall',
	            	thing : {
	            	   positions :res.data.positions,
	        	       color:res.data.color
	        	    }
	           },_this.ctx)
			}else{
				 layer.msg(res?res.message:'系统异常!', {icon: 2});
			}
		}
	});
	_this.drawWall.addListener('error',function(e){
	});
	_this.drawWall.addListener('complete',function(e){
	});
}

SceneWallLibrary.prototype.editEPolyline=function(obj){
	var _this = this;
	_this.model=obj;
	if (_this.isOpenEditEPolyline) {
		_this.closeEditTool();
		_this.loadFormData();
		_this.insTb.reload();
		return;
	}
	layer.load(2);
	var res = common_ajax.ajaxFunc('get', _this.ctx + "/scene/polyline/edit", {}, "html", null);
	layer.closeAll('loading');
	if (!res) {
		layer.alert('系统异常！');
		return;
	}
	layer.open({
		id: 'EditEPolyline',
		title: '属性编辑',
		type: 1,
		offset: '40px',
		area: '300px',
		content: res,
		shade: 0,
		offset: 'l',
		skin: 'layui-layer layui-layer-adminRight layui-layer-city',
		success: function(layero, dIndex) {
			_this.isOpenEditEPolyline = true;
			_this.EditEPolylineIndex = dIndex;
			$(layero).children('.layui-layer-content').css('overflow', 'hidden');
			$(layero).children('.layui-layer-content').css('height', 'calc(100% - 30px)');
			_this.loadFormData();
			_this.renderForm();
			form.render();
		},
		end: function() {
			_this.isOpenEditEPolyline = false;
			_this.EditEPolylineIndex = null;
			_this.closeEditTool();
		}
	});
}

SceneWallLibrary.prototype.renderForm = function(){
	var _this = this;
	
	$('#scenepolylineName').on('input', function() {
		 if(_this.model){
			 _this.model.updateName($("#scenepolylineName").val());
		 }
	 });
	
	$('#scenepolylineCode').on('input', function() {
		 if(_this.model){
			 _this.model.updateCode($("#scenepolylineCode").val());
		 }
	 });
	
	$('#polyline-width').on('input', function() {
		 if(_this.model){
			 _this.model.updateWidth($("#polyline-width").val());
		 }
	 });
	
	form.on('select(clampToGround)', function(data){
		 if(_this.model){
			 _this.model.updateClampToGround(data.value);
		 }
	});
	
	form.on('select(classificationType)', function(data){
		 if(_this.model){
			 _this.model.updateClassificationType(data.value);
		 }
	});
	form.on('select(arcType)', function(data){
		 if(_this.model){
			 _this.model.updateArcType(data.value);
		 }
	});
	
	//颜色
	colorpicker.render({
		elem: '#polyline-color',
		color: (_this.model.thing&&_this.model.thing.color)?_this.model.thing.color:null,
		format: 'rgb',
		predefine: true,
		alpha: true,
		done: function(color) {
			$('#polyline-color-input').val(color); //向隐藏域赋值
			color || this.change(color); //清空时执行 change
		},
		change: function(color) {
			 if(_this.model){
				 _this.model.updateMaterial({
					 color:color,
				 });
			 }
		}
	}); 
	
	$('#polyline-glowPower').on('input', function() {
		 if(_this.model){
			 _this.model.updateMaterial({
				 glowPower:$("#polyline-glowPower").val(),
			 });
		 }
	 });
	
	$('#polyline-taperPower').on('input', function() {
		 if(_this.model){
			 _this.model.updateMaterial({
				 taperPower:$("#polyline-taperPower").val(),
			 });
		 }
	 });	
	
	colorpicker.render({
		elem: '#polyline-outlineColor',
		color: (_this.model.thing&&_this.model.thing.color)?_this.model.thing.color:null,
		format: 'rgb',
		predefine: true,
		alpha: true,
		done: function(color) {
			$('#polyline-outlineColor-input').val(color); //向隐藏域赋值
			color || this.change(color); //清空时执行 change
		},
		change: function(color) {
			 if(_this.model){
				 _this.model.updateMaterial({
					 outlineColor:color,
				 });
			 }
		}
	}); 
	
	$('#polyline-outlineWidth').on('input', function() {
		 if(_this.model){
			 _this.model.updateMaterial({
				 outlineWidth:$("#polyline-outlineWidth").val(),
			 });
		 }
	 });
	
	colorpicker.render({
		elem: '#polyline-gapColor',
		color: (_this.model.thing&&_this.model.thing.color)?_this.model.thing.color:null,
		format: 'rgb',
		predefine: true,
		alpha: true,
		done: function(color) {
			$('#polyline-gapColor-input').val(color); //向隐藏域赋值
			color || this.change(color); //清空时执行 change
		},
		change: function(color) {
			 if(_this.model){
				 _this.model.updateMaterial({
					 gapColor:color,
				 });
			 }
		}
	}); 

	$('#polyline-dashLength').on('input', function() {
		 if(_this.model){
			 _this.model.updateMaterial({
				 dashLength:$("#polyline-dashLength").val(),
			 });
		 }
	});
	
	$('#polyline-dashPattern').on('input', function() {
		 if(_this.model){
			 _this.model.updateMaterial({
				 dashPattern:$("#polyline-dashPattern").val(),
			 });
		 }
	 });
	
	form.on('select(isDistanceDisplay)', function(data){
		 if(_this.model){
			 _this.model.isDistanceDisplay(data.value);
		 }
	});
	
	$('#distanceDisplayNear').on('input', function() {
		 if(_this.model){
			 _this.model.updateDistanceDisplayCondition($("#distanceDisplayNear").val(),null);
		 }
	});
	
	$('#distanceDisplayFar').on('input', function() {
		 if(_this.model){
			 _this.model.updateDistanceDisplayCondition(null,$("#distanceDisplayFar").val());
		 }
	});
	
	form.on('submit(submitPolylineEditForm)', function(data) {
		layer.load(2);
		var formData = {};
		for (var key in data.field) {
			formData['scenePolyline.' + key] = data.field[key];
		}
		var res = common_ajax.ajaxFunc('post', _this.ctx + "/scene/polyline/save", formData, "json", null);
		layer.closeAll('loading');
		if (res && 200 == res.code) {
			layer.msg(res.message, {icon: 1});
			if(_this.model){
				_this.model.updateName(res.data);
		 	}
			if(_this.icondIndex){
				layer.close(_this.icondIndex);
			}
		} else {
			layer.msg(res.message, {icon: 2});
		}
		return false;
	});
}

SceneWallLibrary.prototype.loadFormData=function(){
	let _this=this;
	let data={};
	if(_this.model){
		data={
			id:_this.model.id,
			name:_this.model.name||'',
			code:_this.model.code||'',
			positions:JSON.stringify(_this.model.thing.positions),
			width:_this.model.thing.width||1,
			clampToGround:_this.model.thing.clampToGround||'0',
			classificationType:_this.model.thing.classificationType||'BOTH',
			distanceDisplayNear:_this.model.thing.distanceDisplayNear,
			distanceDisplayFar:_this.model.thing.distanceDisplayFar,
			materialType:_this.model.thing.materialType,
			color:_this.model.thing.color,
			glowPower:_this.model.thing.glowPower||0.25,
			taperPower:_this.model.thing.taperPower||0.5,
			outlineColor:_this.model.thing.outlineColor,
			outlineWidth:_this.model.thing.outlineWidth||0,
			gapColor:_this.model.thing.gapColor,
			dashLength:_this.model.thing.dashLength,
			dashPattern:_this.model.thing.dashPattern,
			arcType:_this.model.thing.arcType,
		}	
	}
	form.val('polylineEditForm', data);
	_this.tabMaterialType();
	_this.createEditTool();
	return data;
}

SceneWallLibrary.prototype.getImage = function(obj) {
	if(obj.thing && obj.thing.image && obj.thing.image.indexOf(this.ctx) != -1){
		return obj.thing.image.substring(this.ctx.length,obj.thing.image.length)
	}
	return obj.thing.image;
}

SceneWallLibrary.prototype.renderProperty = function(){
	var _this = this;
	_this.insTb=table.render({
	    elem: '#tablePolylineProperty',
	    url: _this.ctx +'/scene/property/listData',
	    page: false,
	    where:{
	    	thingId:_this.model.id
	    },
	    cols: [[
	        {field: 'label', sort: false, title: '标签', edit: 'text'},
	        {field: 'value', sort: false, title: '值', edit: 'text'},
	        {align: 'center', toolbar: '#tablePolylinePropertyScript', title: '操作',width:120}
	    ]]
	});
	
    // 添加
    $('#addPolylinePropertyBtn').click(function () {
        showEditModel();
    });

    // 工具条点击事件
    table.on('tool(tablePolylineProperty)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'edit') { // 修改
            showEditModel(data);
        } else if (layEvent === 'del') { // 删除
            doDel(obj);
        }
        
    });

    // 删除
    function doDel(obj) {
        layer.confirm('确定要删除“' + obj.data.label + '”吗？', {
            skin: 'layui-layer-admin',
            shade: .1
        }, function (i) {
            layer.close(i);
            layer.load(2);
    		var res = common_ajax.ajaxFunc('post', _this.ctx + "/scene/property/delete", {id:obj.data.id}, "json", null);
            layer.closeAll('loading');
            if (res.code == 200) {
                layer.msg(res.message, {icon: 1});
				_this.insTb.reload();
            } else {
                layer.msg(res.message, {icon: 2});
            }
        });
    }

    // 显示编辑弹窗
    function showEditModel(nData) {
        layer.open({
            type: 1,
            title: (nData ? '修改' : '添加'),
            content: $('#polylinePropertyScript').html(),
            success: function (layero, dIndex) {
				$(layero).children('.layui-layer-content').css('overflow', 'hidden');
                form.val('polylinePropertyForm', nData);  // 回显数据
                form.on('submit(modelSubmitPolylinePropertyForm)', function (data) {
                    layer.load(2);
                    var formData={}; 
                    for(var key in data.field){
                    	formData['sceneProperty.'+key]=data.field[key];
                    }
                    formData['sceneProperty.thingId']=_this.model.id; 
                    formData['sceneProperty.sceneId']=_this.sceneId; 
            		var res = common_ajax.ajaxFunc('post', _this.ctx + "/scene/property/save", formData, "json", null);
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.close(dIndex);
                        layer.msg(res.message, {icon: 1});
                        _this.insTb.reload({where:{
                	    	thingId:_this.model.id
                	    }}, 'data');
                        let sensor=_this.globe.getById(_this.thingId);
                        if(sensor){
                        	sensor.updateProperty(res.data);
                        }
                        
                    } else {
                        layer.msg(res.message, {icon: 2});
                    }
                    return false;
                });
            }
        });
    }
}

SceneWallLibrary.prototype.delete = function(obj){
	let _this=this;
	if(!obj){
		layer.alert('删除失败，刷新重试！');
		return;
	}
	layer.load(2);
	var res = common_ajax.ajaxFunc('get', _this.ctx + "/scene/polyline/delete", {id:obj.id},"json", null);
	layer.closeAll('loading');
	if (res && 200==res.code) {
        layer.msg(res.message, {icon: 1});
		_this.close();
		_this.closeEditTool();		
		_this.globe.remove(obj.id);
        return true;
    } else {
        layer.msg(res.message, {icon: 2});
        return false;
    }
}

SceneWallLibrary.prototype.tabMaterialType = function(){
	let _this=this;
	if ('line' == _this.model.thing.materialType) {
		$("#polyline-glowPower-tr").css('display','none'); 
		$("#polyline-taperPower-tr").css('display','none'); 
		$("#polyline-outlineWidth-tr").css('display','none'); 
		$("#polyline-outlineColor-tr").css('display','none'); 
		$("#polyline-gapColor-tr").css('display','none'); 
		$("#polyline-dashLength-tr").css('display','none');
		$("#polyline-dashPattern-tr").css('display','none');

	} else if ('glow' == _this.model.thing.materialType) {
		$("#polyline-glowPower-tr").css('display',''); 
		$("#polyline-taperPower-tr").css('display',''); 
		$("#polyline-outlineWidth-tr").css('display','none'); 
		$("#polyline-outlineColor-tr").css('display','none'); 
		$("#polyline-gapColor-tr").css('display','none'); 
		$("#polyline-dashLength-tr").css('display','none');
		$("#polyline-dashPattern-tr").css('display','none');

	} else if ('outline' == _this.model.thing.materialType) {
		$("#polyline-glowPower-tr").css('display','none'); 
		$("#polyline-taperPower-tr").css('display','none'); 
		$("#polyline-outlineWidth-tr").css('display',''); 
		$("#polyline-outlineColor-tr").css('display',''); 
		$("#polyline-gapColor-tr").css('display','none'); 
		$("#polyline-dashLength-tr").css('display','none');
		$("#polyline-dashPattern-tr").css('display','none');

	} else if ('dash' == _this.model.thing.materialType) {
		$("#polyline-glowPower-tr").css('display','none'); 
		$("#polyline-taperPower-tr").css('display','none'); 
		$("#polyline-outlineWidth-tr").css('display','none'); 
		$("#polyline-outlineColor-tr").css('display','none'); 
		
		$("#polyline-gapColor-tr").css('display',''); 
		$("#polyline-dashLength-tr").css('display','');
		$("#polyline-dashPattern-tr").css('display','');
	} else if ('arrow' == _this.model.thing.materialType) {
		$("#polyline-glowPower-tr").css('display','none'); 
		$("#polyline-taperPower-tr").css('display','none'); 
		$("#polyline-outlineWidth-tr").css('display','none'); 
		$("#polyline-outlineColor-tr").css('display','none'); 
		$("#polyline-gapColor-tr").css('display','none'); 
		$("#polyline-dashLength-tr").css('display','none');
		$("#polyline-dashPattern-tr").css('display','none');
	}else{
		$("#polyline-glowPower-tr").css('display','none'); 
		$("#polyline-taperPower-tr").css('display','none'); 
		$("#polyline-outlineWidth-tr").css('display','none'); 
		$("#polyline-outlineColor-tr").css('display','none'); 
		$("#polyline-gapColor-tr").css('display','none'); 
		$("#polyline-dashLength-tr").css('display','none');
		$("#polyline-dashPattern-tr").css('display','none');
	}
}

SceneWallLibrary.prototype.createEditTool=function(){
	let _this=this;
	_this.EditEPolylineTool=_this.globe.createEditEPolyline(_this.model);
	_this.EditEPolylineTool.on('change',function(positions){
		if(positions){
			$('#polyline-positions').val(JSON.stringify(positions)); //向隐藏域赋值
		}
	});
	_this.EditEPolylineTool.on('destroy',function(){
	});
}

SceneWallLibrary.prototype.closeEditTool=function(){
	let _this=this;
	if(_this.EditEPolylineTool){
		_this.EditEPolylineTool.destroy();
		_this.EditEPolylineTool=null;
	}
}

SceneWallLibrary.prototype.close = function(){
	var _this = this;
	if(_this.EditEPolylineIndex){
		layer.close(_this.EditEPolylineIndex);	
	}
}

